package comtgl.demo.utils;

import java.io.*;
import java.net.URL;

public class fileUtil {
    public static File downloadImage(String imageUrl) throws Exception {
// 获取文件扩展名
        String fileExtension = ".jpg";//imageUrl.substring(imageUrl.lastIndexOf("."));
        File file = File.createTempFile("downloaded_image", fileExtension);

// 打开输入流和输出流
        try (InputStream inputStream = new URL(imageUrl).openStream();
             OutputStream outputStream = new FileOutputStream(file)) {

            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("下载图片失败");
        }

        return file;
    }

    public static void main(String[] args) {
        try {
            String imageUrl = "https://hichatx-test.hisense.com/image/684a4813d08e53ed4a91684f/684a4813d08e53ed4a91684e";
            File file = downloadImage(imageUrl);
            System.out.println("图片已保存到: " + file.getAbsolutePath());
        } catch (Exception e) {
            System.err.println("发生错误: " + e.getMessage());
        }
    }
}
